package guanli;

import until.DBUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class UserManagePanel extends JPanel {
    private JTable table;
    private DefaultTableModel model;
    private String role;

    public UserManagePanel(String role) {
        this.role = role;
        setLayout(new BorderLayout());

        // 显示所有字段
        model = new DefaultTableModel(new Object[]{"ID", "用户名", "密码", "电话", "角色"}, 0);
        table = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("添加");
        JButton deleteButton = new JButton("删除");
        JButton updateButton = new JButton("修改");
        JButton refreshButton = new JButton("刷新"); // 添加刷新按钮
        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(refreshButton); // 将刷新按钮加入面板

        add(buttonPanel, BorderLayout.SOUTH);

        loadUsers();

        addButton.addActionListener(e -> addUser());
        deleteButton.addActionListener(e -> deleteUser());
        updateButton.addActionListener(e -> updateUser());
        refreshButton.addActionListener(e -> loadUsers()); // 绑定刷新事件
    }

    private void loadUsers() {
        try (Connection conn = DBUtil.getConnection()) {
            String sql = (role == null || role.equals("全部")) ?
                    "SELECT * FROM users" : "SELECT * FROM users WHERE role = ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            if (role != null && !role.equals("全部")) {
                ps.setString(1, role);
            }
            ResultSet rs = ps.executeQuery();
            model.setRowCount(0); // 清空原有数据
            while (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                String phone = rs.getString("phone");
                String roleValue = rs.getString("role");
                model.addRow(new Object[]{id, username, password, phone, roleValue});
            }
            rs.close();
            ps.close();
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载用户失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void addUser() {
        JTextField usernameField = new JTextField();
        JPasswordField passwordField = new JPasswordField();
        JTextField phoneField = new JTextField();
        JTextField roleField = new JTextField(role != null ? role : "");

        JPanel panel = new JPanel(new GridLayout(0, 1));
        panel.add(new JLabel("用户名:"));
        panel.add(usernameField);
        panel.add(new JLabel("密码:"));
        panel.add(passwordField);
        panel.add(new JLabel("电话:"));
        panel.add(phoneField);
        panel.add(new JLabel("角色:"));
        panel.add(roleField);

        int result = JOptionPane.showConfirmDialog(this, panel, "添加用户", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            try (Connection conn = DBUtil.getConnection()) {
                String sql = "INSERT INTO users (username, password, phone, role) VALUES (?, ?, ?, ?)";
                PreparedStatement ps = conn.prepareStatement(sql);
                ps.setString(1, usernameField.getText().trim());
                ps.setString(2, new String(passwordField.getPassword()));
                ps.setString(3, phoneField.getText().trim());
                ps.setString(4, roleField.getText().trim());
                ps.executeUpdate();
                ps.close();
                loadUsers();
                JOptionPane.showMessageDialog(this, "添加成功！");
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "添加用户失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void deleteUser() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) {
            int userId = (int) model.getValueAt(selectedRow, 0);
            int confirm = JOptionPane.showConfirmDialog(this, "确定删除该用户吗？", "确认删除", JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                try (Connection conn = DBUtil.getConnection()) {
                    String sql = "DELETE FROM users WHERE id = ?";
                    PreparedStatement ps = conn.prepareStatement(sql);
                    ps.setInt(1, userId);
                    ps.executeUpdate();
                    ps.close();
                    loadUsers();
                    JOptionPane.showMessageDialog(this, "删除成功！");
                } catch (Exception e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this, "删除用户失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择要删除的用户。", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }

    private void updateUser() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) {
            int userId = (int) model.getValueAt(selectedRow, 0);
            String currentUsername = (String) model.getValueAt(selectedRow, 1);
            String currentPassword = (String) model.getValueAt(selectedRow, 2);
            String currentPhone = (String) model.getValueAt(selectedRow, 3);
            String currentRole = (String) model.getValueAt(selectedRow, 4);

            JTextField usernameField = new JTextField(currentUsername);
            JTextField passwordField = new JTextField(currentPassword);
            JTextField phoneField = new JTextField(currentPhone);
            JTextField roleField = new JTextField(currentRole);

            JPanel panel = new JPanel(new GridLayout(0, 1));
            panel.add(new JLabel("用户名:"));
            panel.add(usernameField);
            panel.add(new JLabel("密码:"));
            panel.add(passwordField);
            panel.add(new JLabel("电话:"));
            panel.add(phoneField);
            panel.add(new JLabel("角色:"));
            panel.add(roleField);

            int result = JOptionPane.showConfirmDialog(this, panel, "修改用户", JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.OK_OPTION) {
                try (Connection conn = DBUtil.getConnection()) {
                    String sql = "UPDATE users SET username = ?, password = ?, phone = ?, role = ? WHERE id = ?";
                    PreparedStatement ps = conn.prepareStatement(sql);
                    ps.setString(1, usernameField.getText().trim());
                    ps.setString(2, passwordField.getText().trim());
                    ps.setString(3, phoneField.getText().trim());
                    ps.setString(4, roleField.getText().trim());
                    ps.setInt(5, userId);
                    ps.executeUpdate();
                    ps.close();
                    loadUsers();
                    JOptionPane.showMessageDialog(this, "修改成功！");
                } catch (Exception e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this, "修改用户失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择要修改的用户。", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }
}